package com.atguigu.lease.web.app.controller.agreement;


import com.atguigu.lease.common.result.Result;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.LeaseAgreement;
import com.atguigu.lease.model.enums.LeaseStatus;
import com.atguigu.lease.web.app.service.LeaseAgreementService;
import com.atguigu.lease.web.app.vo.agreement.AgreementDetailVo;
import com.atguigu.lease.web.app.vo.agreement.AgreementItemVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/app/agreement")
@Tag(name = "租约信息")
public class LeaseAgreementController {

    @Autowired
    private LeaseAgreementService leaseAgreementService;


    /**
     * 获取个人租约基本信息列表
     * 用户在APP端查看自己的租约列表
     */
    @Operation(summary = "获取个人租约基本信息列表")
    @GetMapping("listItem")
    public Result<List<AgreementItemVo>> listItem(@RequestHeader("access_token") String token) {
        // 从当前登录用户信息中获取用户手机号，查询该用户的所有租约
        List<AgreementItemVo> agreementItemVoList = leaseAgreementService.getAgreementItemListByCurrentUser(token);
        return Result.ok(agreementItemVoList);
    }

    /**
     * 根据id获取租约详细信息
     * 用户点击租约列表中的某一项，查看租约详情
     */
    @Operation(summary = "根据id获取租约详细信息")
    @GetMapping("getDetailById")
    public Result<AgreementDetailVo> getDetailById(
            @Parameter(description = "租约ID", required = true) @RequestParam Long id) {
        AgreementDetailVo agreementDetailVo = leaseAgreementService.getAgreementDetailById(id);
        if (agreementDetailVo == null) {
            return Result.build(null, ResultCodeEnum.DATA_ERROR);
        }
        return Result.ok(agreementDetailVo);
    }

    /**
     * 根据id更新租约状态
     * 用于确认租约和提前退租等操作
     */
    @Operation(summary = "根据id更新租约状态", description = "用于确认租约和提前退租")
    @PostMapping("updateStatusById")
    public Result updateStatusById(
            @Parameter(description = "租约ID", required = true) @RequestParam Long id,
            @Parameter(description = "租约状态", required = true) @RequestParam LeaseStatus leaseStatus) {
        boolean success = leaseAgreementService.updateAgreementStatus(id, leaseStatus);
        if (!success) {
            return Result.fail();
        }
        return Result.ok();
    }

    /**
     * 保存或更新租约
     * 主要用于续约功能，可以创建新的租约或更新已有租约
     */
    @Operation(summary = "保存或更新租约", description = "用于续约")
    @PostMapping("saveOrUpdate")
    public Result saveOrUpdate(@RequestBody LeaseAgreement leaseAgreement) {
        boolean success = leaseAgreementService.saveOrUpdateAgreement(leaseAgreement);
        if (!success) {
            return Result.fail();
        }
        return Result.ok();
    }
}